package com.zlx.xbhy.webSocket;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 周罗校
 * @Description webSocket地址信息
 * @ClassName WebSocketServer
 * @date 2020.12.05 10:49:58
 * 该版权归周罗校所有，最终解释权以官方为准
 */
@Component
@ServerEndpoint("/webSocket/{userId}")
public class WebSocketServer {

    public static final Map<Long,Session> map=new HashMap<>();
    private static Integer onLineCount=0;


    @OnOpen
    public void onOpen(Session session,@PathParam("userId") Long userId) {
        System.out.println(userId+"上线了");
        //用户上线
        map.put(userId,session);
        onLineCount++;
    }

    /**
     * 客户端关闭
     * @param session session
     */
    @OnClose
    public void onClose(Session session,@PathParam("userId") Long userId) {
        map.remove(userId);
        onLineCount--;
    }
    /**
     * @Author 周罗校
     * @Description 信息单发
     * @Param [userId, msg]
     * @return void
     * @Date 2020.12.05 11:19:53
     **/
    public static void sendMsg(Long userId,String msg){
        System.out.println("发送信息");
        if(map.get(userId)!=null) {
            System.out.println("发送信息成功");
            map.get(userId).getAsyncRemote().sendText(msg);
        }
    }
    /**
     * @Author 周罗校
     * @Description 群发
     * @Param [msg]
     * @return void
     * @Date 2020.12.05 11:21:16
     **/
    public static void sendMsg(String msg){
        map.forEach((id,seeeion)->{
            seeeion.getAsyncRemote().sendText(msg);
        });
    }
}
